package com.example.rfb.serviceloader.app_compiler;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class ServicesFiles {
    public static final String SERVICES_PATH = "META-INF/services";

    private ServicesFiles() {
    }

    static String getPath(String serviceName) {
        return "META-INF/services/" + serviceName;
    }

    static Set<String> readServiceFile(InputStream input) throws IOException {
        HashSet<String> serviceClasses = new HashSet();

        BufferedReader reader = null;
        InputStreamReader inputStreamReader = null;

        try {

            inputStreamReader = new InputStreamReader(input, StandardCharsets.UTF_8);
            reader = new BufferedReader(inputStreamReader);


            String line;
            while((line = reader.readLine()) != null) {
                int commentStart = line.indexOf(35);
                if (commentStart >= 0) {
                    line = line.substring(0, commentStart);
                }

                line = line.trim();
                if (!line.isEmpty()) {
                    serviceClasses.add(line);
                }
            }

            HashSet var11 = serviceClasses;
            return var11;
        } catch (Throwable var9) {
            throw var9;
        } finally {

            if(inputStreamReader != null){
                inputStreamReader.close();
            }

            if(reader != null){
                reader.close();
            }

            if(input != null){
                input.close();
            }
        }
    }

    static void writeServiceFile(Collection<String> services, OutputStream output) throws IOException {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8));
        Iterator var3 = services.iterator();

        while(var3.hasNext()) {
            String service = (String)var3.next();
            writer.write(service);
            writer.newLine();
        }

        writer.flush();
    }
}
